package cn.yunyichina.provider.pay.icbc.utils;

import java.io.*;
import java.util.*;

import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.*;

public class XMLParsor {

	private String xmlFileName;

	public String strText;

	SAXBuilder builder;

	public String dir;

	// 构造器
	public XMLParsor(String xmlFileName) {
		this.xmlFileName = xmlFileName;
		strText = null;
		builder = new SAXBuilder();
	}

	public boolean read(String strRoute, String strElement, int flag) {
		//SAXBuilder builder=new SAXBuilder();
		strText = null;
		try {
			String[] route = new String[4];

			String str = null;
			Document doc = builder.build(xmlFileName);
			Element root = doc.getRootElement();
			Element element = root;

			//创建一个拆分字符串内容的对象,每次返回一项
			StringTokenizer st = new StringTokenizer(strRoute, ":");
			str = st.nextToken();

			while (st.hasMoreTokens()) {
				str = st.nextToken();
				element = element.getChild(str);
			}

			//mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,str);
			element = (Element) element.getParent();
			/*
			 * while(flag!=1) { if(element.removeChild(str))
			 * mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"deleted "+str);
			 * else mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"not
			 * deleted");
			 * 
			 * flag--; }
			 */
			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,element.getName());
			strText = element.getChild(str).getChild(strElement).getText();

		} catch (JDOMException jdome) {
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, xmlFileName
					+ " is not well-formed");

		} catch (IOException ioe) {
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, ioe);

		} catch (NullPointerException nullpe) {
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "not founded"
					+ "\n" + nullpe);

		} catch (Exception e) {
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "read no succeed"
					+ "\n" + e);

		}

		if (strText == null) {
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "not founded");
			return false;
		} else {
			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"strText="+strText);
			return true;
		}

	}

	//改写XML文件的某一元素的值
	//strRoute为XML文件从根元素开始到该元素的父元素的路径
	//strElement为需要读取的元素
	//flag为当XML含有多个同名元素时，需要改写元素所处的序号
	public void write(String strRoute, String strElement, String strSet,
			int flag) {
		//SAXBuilder builder=new SAXBuilder();
		try {
			String str = null;
			Document doc = builder.build(xmlFileName);
			Element root = doc.getRootElement();
			Element element = root;

			StringTokenizer st = new StringTokenizer(strRoute, ":");
			str = st.nextToken();

			while (st.hasMoreTokens()) {
				str = st.nextToken();
				//mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,str);
				element = element.getChild(str);

			}

			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"test :"+str);
			element = (Element) element.getParent();

			//若需要改写的不是XML文件的第一个同名元素，则获取该元素
			//方法为:将之前的元素依次移到后面，需要改写的元素前移至第一个
			/*
			 * if(flag>1) { int j=flag; while(j!=1) {
			 * 
			 * Element tmp=element.getChild(str);
			 * element.addContent(tmp.detach()); j--; } }
			 */
			element = element.getChild(str).getChild(strElement);

			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"gettxt
			// "+element.getText());

			element.setText(strSet);

			//若需要改写的不是XML文件的第一个同名元素
			//上面改变了次序，需要在成功改写后恢复原有次序
			/*
			 * if(flag!=1) {
			 * 
			 * java.util.List children=element.getChildren(); Iterator
			 * iterator=children.iterator(); int count=0;
			 * while(iterator.hasNext()) { Element
			 * child=(Element)iterator.next(); count++; }
			 * 
			 * System.out.println("count"+count);
			 * 
			 * k=(count+1-flag)%count;
			 * 
			 * while(k!=0) { Element tmp=element.getChild(str);
			 * element.addContent(tmp.detach()); k--; } }
			 *  
			 */
			XMLOutputter outputter = new XMLOutputter("", false, "GB2312");
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new FileWriter(xmlFileName)));

			Document myDocument = root.getDocument();

			outputter.output(myDocument, out);
			out.close();

		} catch (JDOMException jdome) {
			jdome.printStackTrace();
//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, xmlFileName
//					+ " is not well-formed\n");

		} catch (IOException ioe) {
			ioe.printStackTrace();
//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, ioe);

		} catch (Exception e) {
			e.printStackTrace();
//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,
//					"write not succeed\n");

		}

	}
	/*
	 * para: Element start ,开始查找节点
	 * para: sNodeName 查找的节点名 
	 */
	public Element getNode(Element start ,String sNodeName)
	{
		Element target=null;
		target=findNode(start,sNodeName);
		return target;
	}
	/*
	 * 递归完成查找
	 * para: Element root 开始查找节点
	 */
	public Element findNode(Element root,String sNodeName)
	{
		Element node =null;
		try
		{
			String sName="";
			List list=root.getChildren();
			for(int i=0;i<list.size();i++)
			{
				node=(Element)list.get(i);
				sName=node.getName();
				sName=sName.trim();
				//System.err.println("node name:"+sName+"-"+sNodeName);
				if(sName.equals(sNodeName))
				{
					System.err.println("find the node:"+sName);
					return node;
				}
				node=findNode(node,sNodeName);
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
			System.err.println("error:"+ex.getMessage());
		}
		return node;
	}
	/**
	 *  填写包的公共部分
	 * @param root	开始节点
	 * @param map	参数map
	 * @param sCycName	循环节点名
	 * @return
	 */
	public Element writePublicNode(Element root,HashMap map,String sCycName)
	{
		Element node=null;
		try
		{
			String sName="";
			String sValue="";
			List list=root.getChildren();
			for(int i=0;i<list.size();i++)
			{
				node=(Element)list.get(i);
				sName=node.getName();
				sName=sName.trim();
				sValue=(String)map.get(sName);
				//System.err.println("sName:"+sName+":"+sValue);
				if(sCycName.equals(sName))
				{
					//System.err.println("find cyc node:"+sName );
					return node;
				}
				else if(sValue!=null && !"".equals(sValue) )
					node.setText(sValue);
				node=writePublicNode(node,map,sCycName);
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
			System.err.println("error:"+ex.getMessage());
		}
		return node;
	}
	/**
	 *  填写包的交易参数
	 * @param cycNode 循环节点
	 * @param list	参数list
	 * @return  
	 */
	public boolean writeCycNode(Element cycNode,ArrayList list)
	{
		if(cycNode==null|| list==null)
			return false;
		HashMap map=null;
		Element start=cycNode;
		//循环填充交易参数，循环节点从list中第2个map开始。
		for(int i=2;i< list.size(); i++)
		{
			map=(HashMap)list.get(i);
			if(i>2)
				start=addCycNode(start);
			writeParaMap(start,map);
		}
		return true;
	}
	/**
	 *  新增循环节点
	 * @param cycNode 循环节点
	 * @return
	 */
	public Element addCycNode(Element cycNode)
	{
		Element node=cycNode;
		Element child=null;
		Element newNode=null;
		Element tmpNode=null;
		String sName="";
		if(cycNode==null)
			return newNode;
		newNode=new Element(node.getName());
		node.getParent().addContent(newNode);
		List cList=node.getChildren();
		for(int i=0;i<cList.size();i++)
		{
			child=(Element)cList.get(i);
			sName=child.getName();
			sName=sName.trim();
			tmpNode=new Element(sName);
			newNode.addContent(tmpNode);
		}
		return newNode;
	}
	/** 
	 * 
	 * @param map	需要写入的参数map
	 * @param start 开始节点
	 * @param bNew  是否新增节点再写入参数
	 * @return
	 */
	public void writeParaMap(Element start,HashMap map)
	{
		try
		{
			String sName="";
			String sValue="";
			Element node=null;
			List list=start.getChildren();
			for(int i=0;i<list.size();i++)
			{
				node=(Element)list.get(i);
				sName=node.getName();
				sName=sName.trim();
				sValue=(String)map.get(sName);
				if(sValue!=null && !"".equals(sValue) );
					node.setText(sValue);
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
			System.err.println("error:"+ex.getMessage());
		}
		return ;
	}
	/**
	 * 
	 * @param list	参数列表
	 */
	public void writeParaList(ArrayList list)
	{
		
		try {
			String sCaseName="";
			String sItem="";
			String sCycName="";
			HashMap map=null;
			Document doc = builder.build(xmlFileName);
			Element root = doc.getRootElement();
			Element element = root;
			Element cycNode=null;
			
			map=(HashMap)list.get(0);	//参数文件map
			sItem="Description";
			sCaseName=(String)map.get(sItem);
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "Description=" + sCaseName );
		
			sItem="CysName";
			sCycName=(String)map.get(sItem);
			
			map=(HashMap)list.get(1);	//public 参数map
			cycNode=writePublicNode(element,map,sCycName);
			
			if( writeCycNode(cycNode,list)==false)	//循环 参数
			  System.err.println(" write cyc node fail");
			
			XMLOutputter outputter = new XMLOutputter("", false, "GB2312");
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new FileWriter(xmlFileName)));

			Document myDocument = root.getDocument();
			outputter.output(myDocument, out);
			out.close();

		} catch (JDOMException jdome) {
			jdome.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	/**
	 * 
	 * @param strRoute
	 * @param strElement
	 * @param strSet
	 * @param flag
	 */
	public void writeGBK(String strRoute, String strElement, String strSet,
			int flag) {
		//SAXBuilder builder=new SAXBuilder();
		try {
			String str = null;
			Document doc = builder.build(xmlFileName);
			Element root = doc.getRootElement();
			Element element = root;

			StringTokenizer st = new StringTokenizer(strRoute, ":");
			str = st.nextToken();

			while (st.hasMoreTokens()) {
				str = st.nextToken();
				//mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,str);
				element = element.getChild(str);

			}

			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"test :"+str);
			element = (Element) element.getParent();

			//若需要改写的不是XML文件的第一个同名元素，则获取该元素
			//方法为:将之前的元素依次移到后面，需要改写的元素前移至第一个
			/*
			 * if(flag>1) { int j=flag; while(j!=1) {
			 * 
			 * Element tmp=element.getChild(str);
			 * element.addContent(tmp.detach()); j--; } }
			 */
			element = element.getChild(str).getChild(strElement);

			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"gettxt
			// "+element.getText());

			element.setText(strSet);

			//若需要改写的不是XML文件的第一个同名元素
			//上面改变了次序，需要在成功改写后恢复原有次序
			/*
			 * if(flag!=1) {
			 * 
			 * java.util.List children=element.getChildren(); Iterator
			 * iterator=children.iterator(); int count=0;
			 * while(iterator.hasNext()) { Element
			 * child=(Element)iterator.next(); count++; }
			 * 
			 * System.out.println("count"+count);
			 * 
			 * k=(count+1-flag)%count;
			 * 
			 * while(k!=0) { Element tmp=element.getChild(str);
			 * element.addContent(tmp.detach()); k--; } }
			 *  
			 */
			XMLOutputter outputter = new XMLOutputter("", false, "GBK");
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new FileWriter(xmlFileName)));

			Document myDocument = root.getDocument();

			outputter.output(myDocument, out);
			out.close();

		} catch (JDOMException jdome) {
			jdome.printStackTrace();
//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, xmlFileName
//					+ " is not well-formed\n");

		} catch (IOException ioe) {
			ioe.printStackTrace();
//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, ioe);

		} catch (Exception e) {
			e.printStackTrace();
//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,
//					"write not succeed\n");

		}

	}
	
	public void write2(String strRoute, String strElement, String strSet,
			int flag) {

		//SAXBuilder builder=new SAXBuilder();
		try {
			String str = null;
			Document doc = builder.build(xmlFileName);
			Element root = doc.getRootElement();
			Element element = root;

			StringTokenizer st = new StringTokenizer(strRoute, ";");
			str = st.nextToken();

			while (st.hasMoreTokens()) {
				str = st.nextToken();
				//mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,str);
				element = element.getChild(str);

			}

			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"test :"+str);
			element = (Element) element.getParent();

			//若需要改写的不是XML文件的第一个同名元素，则获取该元素
			//方法为:将之前的元素依次移到后面，需要改写的元素前移至第一个
			/*
			 * if(flag>1) { int j=flag; while(j!=1) {
			 * 
			 * Element tmp=element.getChild(str);
			 * element.addContent(tmp.detach()); j--; } }
			 */
			element = element.getChild(str).getChild(strElement);

			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"gettxt
			// "+element.getText());

			element.setText(strSet);

			//若需要改写的不是XML文件的第一个同名元素
			//上面改变了次序，需要在成功改写后恢复原有次序
			/*
			 * if(flag!=1) {
			 * 
			 * java.util.List children=element.getChildren(); Iterator
			 * iterator=children.iterator(); int count=0;
			 * while(iterator.hasNext()) { Element
			 * child=(Element)iterator.next(); count++; }
			 * 
			 * System.out.println("count"+count);
			 * 
			 * k=(count+1-flag)%count;
			 * 
			 * while(k!=0) { Element tmp=element.getChild(str);
			 * element.addContent(tmp.detach()); k--; } }
			 *  
			 */
			XMLOutputter outputter = new XMLOutputter("", false, "GB2312");
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new FileWriter(xmlFileName)));

			Document myDocument = root.getDocument();

			outputter.output(myDocument, out);
			out.close();

		} catch (JDOMException jdome) {
			//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, xmlFileName
			//					+ " is not well-formed" + "\n" + jdome);
			System.out.println("[" + Tools.getDateTime2() + "]XML数据文件："
					+ xmlFileName + "  不正确！！");
			jdome.printStackTrace();

		} catch (IOException ioe) {
			//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, ioe);
			System.out.println("[" + Tools.getDateTime2() + "]IO出错！！");
			ioe.printStackTrace();
		} catch (Exception e) {
			//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "write not
			// succeed"
			//					+ "\n" + e);
			System.out.println("[" + Tools.getDateTime2() + "]未知错误！！");
			e.printStackTrace();

		}

	}
	/**
	 * 
	 * @param 普通版list	参数列表
	 */
	public void writeptParaList(ArrayList list)
	{
		
		try {
			String sCaseName="";
			String sItem="";
			String sCycName="";
			HashMap map=null;
			Document doc = builder.build(xmlFileName);
			Element root = doc.getRootElement();
			Element element = root;
			Element cycNode=null;
			
			map=(HashMap)list.get(0);	//参数文件map
			sItem="Description";
			sCaseName=(String)map.get(sItem);
			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "Description=" + sCaseName );
		
			sItem="CysName";
			sCycName=(String)map.get(sItem);
			
			map=(HashMap)list.get(1);	//public 参数map
			cycNode=writeptPublicNode(element,map,sCycName);
			
			if( writeCycNode(cycNode,list)==false)	//循环 参数
			  System.err.println(" write cyc node fail");
			
			XMLOutputter outputter = new XMLOutputter("", false, "GB2312");
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new FileWriter(xmlFileName)));

			Document myDocument = root.getDocument();
			outputter.output(myDocument, out);
			out.close();

		} catch (JDOMException jdome) {
			jdome.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 *  普通版填写包的公共部分
	 * @param root	开始节点
	 * @param map	参数map
	 * @param sCycName	循环节点名
	 * @return
	 */
	public Element writeptPublicNode(Element root,HashMap map,String sCycName)
	{
		Element node=null;
		try
		{
			String sName="";
			String sValue="";
			List list=root.getChildren();
			for(int i=0;i<list.size();i++)
			{
				node=(Element)list.get(i);
				sName=node.getName();
				sName=sName.trim();
				sValue=(String)map.get(sName);
				//System.err.println("sName:"+sName+":"+sValue);
				if(sCycName.equals(sName)&&(root.getName()).trim().equals("ReqParamSet"))
				{
					//System.err.println("find cyc node:"+sName );
					return node;
				}
				else if(sValue!=null && !"".equals(sValue) )
					node.setText(sValue);
				node=writeptPublicNode(node,map,sCycName);
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
			System.err.println("error:"+ex.getMessage());
		}
		return node;
	}
}
